package mware_lib;

import java.io.IOException;

import java.util.Hashtable;

import branch_access.Manager;

import cash_access.Account;
import cash_access.AccountSkeleton;

import mware_lib.namensdienst.communication.ObjectConnection;
import mware_lib.namensdienst.communication.Server;
import mware_lib.namensdienst.messages.ManReqMsg;
import mware_lib.namensdienst.messages.ManRetMsg;

public class ManagerSkeleton implements Runnable{

	private Manager bank;
	private Hashtable<String, Account> accountTable;
	private AccountSkeleton as;

	private Server server;
	private boolean running;
	

	public ManagerSkeleton(int managerSkeletonPort, int accountSkeletonPort, Manager bank) {

		this.bank = bank;
		this.accountTable = new Hashtable<String, Account>();
		
		this.as = new AccountSkeleton(accountSkeletonPort, this);
		Thread t = new Thread(as);
		t.start();
		
		running = true;

		try {
			server = new Server(managerSkeletonPort);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		while(running){
			try {
				ObjectConnection myConnection = server.getConnection();

				Object msg;
				msg = myConnection.receive();

				//System.out.println("Manager hat was empfangen!");
				ManRetMsg mrMsg = null;

				if(msg instanceof ManReqMsg){
					ManReqMsg reqMsg = (ManReqMsg)msg;
					if(reqMsg.getMethod().equals("removeAccount")){
						
						try{
							boolean b = bank.removeAccount(reqMsg.getKontoID());
							mrMsg = new ManRetMsg(b);
						}catch (RemoteException e1){
							mrMsg = new ManRetMsg(false);
						}
						
					}else if(reqMsg.getMethod().equals("createAccount")){
						System.out.println("Manager: createAccount");
						mrMsg = new ManRetMsg(bank.createAccount(reqMsg.getOwner()));
					}else{
						System.out.println("ManagerSkeleton receive: Methodtyp unbekannt");
					}
					
					myConnection.send(mrMsg);
				}
				
				myConnection.close();

			} catch (ClassNotFoundException e) {
				throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
			} catch (IOException e) {
				throw new RemoteException(e.getClass().toString() + ": " + e.getMessage(), e);
			}

		}

	}
	
	public void putAccountToTable(String id, cash_access.Account type){
		accountTable.put(id, (Account) type);
	}

	public void removeFromAccountTable(String id){
		accountTable.remove(id);
	}
	
	public synchronized Hashtable<String, Account> getAccountTable(){
		return accountTable;
	}
	
}










